// Spli File
// By Ben 23:35 24/09/2016

#include <iostream>
#include <Windows.h>


using namespace std;
using std::cout;
using std::endl;

DWORD GetAFilesize(string Filename){
	HANDLE fh;
	wstring wFilename;
	DWORD fsize = 0;
	//Convert string to wide string
	wFilename = wstring(Filename.begin(), Filename.end());
	//Set  a handle to the file below.
	fh = CreateFile(wFilename.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, 0);
	if (fh == INVALID_HANDLE_VALUE){
		return 0;
	}
	//Get filesize using files handle
	fsize = GetFileSize(fh, NULL);
	//Close file.
	CloseHandle(fh);
	//Return size
	return fsize;
}

int main(int argc, char *argv[]){

	string InFile = "C:\\ben\\AdminGuide.chm";
	string sFolder = "C:\\ben\\parts\\";
	string sOrgFile = InFile;
	string sJoinBat = "C:\\ben\\parts\\join.bat";

	char num[10];
	char sOutPath[MAX_PATH];
	char sJoinFile[MAX_PATH];
	unsigned char c = '\0';
	
	//File vars
	FILE *fin = nullptr;
	FILE *fout = nullptr;
	
	int pos = string::npos;
	int parts = 8;

	long double count = 0;
	long double split_size = 0;
	long double fReadBytes = 0;

	//Get size of original file.
	DWORD fsize = GetAFilesize(InFile);

	//Look for slash slash in originl filename
	pos = sOrgFile.find_last_of('\\');

	if (pos != string::npos){
		//Remove file path just keep filename.
		sOrgFile.erase(0, pos + 1);
	}

	//Get the the size of each file part
	split_size = (fsize / parts);

	//Open the original file to be split.
	fin = fopen(InFile.c_str(), "rb");

	if (!fin){
		cout << "IO/ERROR Cannot open input file." << endl;
		exit(1);
	}

	//Start of out join batch file
	strcpy(sJoinFile, "@ECHO OF\n");
	strcat(sJoinFile, "CLS\n");
	strcat(sJoinFile, "COPY/B ");

	for (count = 0; count < parts; count++){
		//Convert int to char
		itoa(count+1, num, 10);
		//Build the split part filename.
		strcpy(sOutPath, sFolder.c_str());
		strcat(sOutPath, num);
		strcat(sOutPath, ".part");

		//Create split part files.
		fout = fopen(sOutPath, "wb");

		//While fReadBytes is less then splitsize keep reading from input file
		while (fReadBytes < split_size){
			//Get a single char
			c = fgetc(fin);
			//Write c to split part file
			fputc(c, fout);
			//INC counter
			fReadBytes++;
		}
		//Build the text line that will be used to join the files
		if (count < parts - 1){
			strcat(sJoinFile, num);
			strcat(sJoinFile, ".part + ");
		}
		//Clear up
		fReadBytes = 0;
		fclose(fout);
	}

	//Append last file part.
	strcat(sJoinFile, num);
	strcat(sJoinFile, ".part ");
	
	//Append original filename.
	strcat(sJoinFile, sOrgFile.c_str());

	//Close input and output files.
	fclose(fin);
	fclose(fout);

	//Create the batch join file.
	fout = fopen(sJoinBat.c_str(), "w");
	fputs(sJoinFile, fout);
	fclose(fout);

	return 0;
}